var host = location.hostname;
	var port = location.port;
var localhost="http://"+host+":"+port+"/CRUD/index.php/";
$(document).ready(function() {
	


   var $calendar = $('#calendar');
//***********************************************
 //var eventosJSON =getEventosJSON();
 var h = getEventData();
 x = new Date();
// console.log("la fecha que busco es: "+x.toJSON());
// console.log(JSON.stringify(h));

//***********************************************
 $("#selectBox").change(function(){
   var sel1Index = document.getElementById("selectBox").selectedIndex;
   var selectBox = document.getElementById("selectBox").options[sel1Index].text; 
   $('#labelTipo').text(selectBox);
   $calendar.weekCalendar("refresh");
   getEventData();
  });
 //*************************************++
$(".today").click(function() {
   $calendar.weekCalendar("today");
});
 //*************************************++
$(".next").click(function() {
   $calendar.weekCalendar("nextWeek");
});
 //*************************************++
$(".prev").click(function() {
   $calendar.weekCalendar("prevWeek");
});
   var id = 10;

   $calendar.weekCalendar({
      timeslotsPerHour : 4,
      allowCalEventOverlap : true,
      overlapEventsSeparate: true,
      firstDayOfWeek : 1,
      businessHours :{start: 6, end: 18, limitDisplay: true },
      daysToShow : 7,
       height : function($calendar) {
         return $(window).height() - $("h1").outerHeight() - 1;
      },
      eventRender : function(calEvent, $event) {
         if (calEvent.end.getTime() < new Date().getTime()) {
            $event.css("backgroundColor", "#aaa");
            $event.find(".wc-time").css({
               "backgroundColor" : "#999",
               "border" : "1px solid #888"
            });
         }
      },
      draggable : function(calEvent, $event) {
         return calEvent.readOnly != true;
      },
      resizable : function(calEvent, $event) {
         return calEvent.readOnly != true;
      },
	  
//***************************************************************  
//registar un nuevo evento aqui la funcion 
//***************************************************************  
      eventNew : function(calEvent, $event) {
         var $dialogContent = $("#event_edit_container");
         resetForm($dialogContent);
         var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
         var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
         var titleField = $dialogContent.find("input[name='title']");
         var bodyField = $dialogContent.find("textarea[name='body']");


         $dialogContent.dialog({
            modal: true,
            title: "Nuevo Envento en Calendario",
            close: function() {
               $dialogContent.dialog("destroy");
               $dialogContent.hide();
               $('#calendar').weekCalendar("removeUnsavedEvents");
            },

//***************************************************************  
 buttons: {
               save : function() {
                  calEvent.id = parseInt(getLastIdEvent())+1;
                  calEvent.start = new Date(startField.val());
				  calEvent.end = new Date(endField.val());
				  calEvent.title = titleField.val();
                  calEvent.body = bodyField.val();
	              
			  	  $calendar.weekCalendar("removeUnsavedEvents");
                  $calendar.weekCalendar("updateEvent", calEvent);
                  $dialogContent.dialog("close");
				  calEvent.id= saveEventosJSON(calEvent);
			   },
			   

//***************************************************************  
               cancel : function() {
                  $dialogContent.dialog("close");
               }
            }
         }).show();

         $dialogContent.find(".date_holder").text($calendar.weekCalendar("formatDate", calEvent.start));
         setupStartAndEndTimeFields(startField, endField, calEvent, $calendar.weekCalendar("getTimeslotTimes", calEvent.start));

      },
	  // Mover evento entre horas y dias
      eventDrop : function(calEvent, $event) {
	         updateMoveEventosJSON(calEvent);
      },
	  
	  // Aumenta la fecha final de evento, igual el renderizado
      eventResize : function(calEvent, $event) {
	        updateMoveEventosJSON(calEvent);
      },
      eventClick : function(calEvent, $event) {
         if (calEvent.readOnly) {
            return;
         }

         var $dialogContent = $("#event_edit_container");
         resetForm($dialogContent);
         var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
         var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
         var titleField = $dialogContent.find("input[name='title']").val(calEvent.title);
         var bodyField = $dialogContent.find("textarea[name='body']");
         bodyField.val(calEvent.body);

         $dialogContent.dialog({
            modal: true,
            title: "Edit - " + calEvent.title,
            close: function() {
               $dialogContent.dialog("destroy");
               $dialogContent.hide();
               $('#calendar').weekCalendar("removeUnsavedEvents");
            },
            buttons: {
               save : function() {

                  calEvent.start = new Date(startField.val());
                  calEvent.end = new Date(endField.val());
                  calEvent.title = titleField.val();
                  calEvent.body = bodyField.val();
//***************************************************************  
//Editando el contenido del evento creado en el calendario
 //alert("editando evento: "+ calEvent.id);
                  $calendar.weekCalendar("updateEvent", calEvent);
				  updateEventosJSON(calEvent);
                  $dialogContent.dialog("close");
//***************************************************************  
 
 },
 
//*************************************************************** 
// Delete event
//***************************************************************  
               "delete" : function() {
			  // alert("eliminando"+calEvent.id);
                  $calendar.weekCalendar("removeEvent", calEvent.id);
				   $.getJSON(localhost+'controler_evento_instalacion_deportiva/evento/delete?id='+calEvent.id); 
        
                  $dialogContent.dialog("close");
               },

//***************************************************************  
               cancel : function() {
                  $dialogContent.dialog("close");
               }
            }
         }).show();

         var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
         var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
         $dialogContent.find(".date_holder").text($calendar.weekCalendar("formatDate", calEvent.start));
         setupStartAndEndTimeFields(startField, endField, calEvent, $calendar.weekCalendar("getTimeslotTimes", calEvent.start));
         $(window).resize().resize(); //fixes a bug in modal overlay size ??

      },
      eventMouseover : function(calEvent, $event) {
      },
      eventMouseout : function(calEvent, $event) {
      },
      noEvents : function() {

      },
      data : 
 function(start, end, callback) {
         callback(getEventData());
      }
   });

   function resetForm($dialogContent) {
      $dialogContent.find("input").val("");
      $dialogContent.find("textarea").val("");
   }
//6fcae7f6d7
   function getEventData() {
      var year = new Date().getFullYear();
      var month = new Date().getMonth();
      var day = new Date().getDate();
	  var fecha =new Date(year, month, day, 12);
	  console.log('"end":'+fecha);
      var json;
	  var sel1Index = document.getElementById("selectBox").selectedIndex;
      var selectBox = document.getElementById("selectBox").options[sel1Index].text; 
      $('#labelTipo').text(selectBox);
	 
	 return getEventosJSON();
   }


   /*
    * Sets up the start and end time fields in the calendar event
    * form for editing based on the calendar event being edited
    */
   function setupStartAndEndTimeFields($startTimeField, $endTimeField, calEvent, timeslotTimes) {

      for (var i = 0; i < timeslotTimes.length; i++) {
         var startTime = timeslotTimes[i].start;
         var endTime = timeslotTimes[i].end;
         var startSelected = "";
         if (startTime.getTime() === calEvent.start.getTime()) {
            startSelected = "selected=\"selected\"";
         }
         var endSelected = "";
         if (endTime.getTime() === calEvent.end.getTime()) {
            endSelected = "selected=\"selected\"";
         }
	
         $startTimeField.append("<option value=\"" + startTime + "\" " + startSelected + ">" + timeslotTimes[i].startFormatted + "</option>");
         $endTimeField.append("<option value=\"" + endTime + "\" " + endSelected + ">" + timeslotTimes[i].endFormatted + "</option>");

      }
      $endTimeOptions = $endTimeField.find("option");
      $startTimeField.trigger("change");
   }

   var $endTimeField = $("select[name='end']");
   var $endTimeOptions = $endTimeField.find("option");

   //reduces the end time options to be only after the start time options.
   $("select[name='start']").change(function() {
      var startTime = $(this).find(":selected").val();
      var currentEndTime = $endTimeField.find("option:selected").val();
      $endTimeField.html(
            $endTimeOptions.filter(function() {
               return startTime < $(this).val();
            })
            );

      var endTimeSelected = false;
      $endTimeField.find("option").each(function() {
         if ($(this).val() === currentEndTime) {
            $(this).attr("selected", "selected");
            endTimeSelected = true;
            return false;
         }
      });

      if (!endTimeSelected) {
         //automatically select an end date 2 slots away.
         $endTimeField.find("option:eq(1)").attr("selected", "selected");
      }

   });
});

/**************************************************/
/**************************************************/
function getLastIdEvent() {
    var result = null;
    var url = localhost+"controler_evento_instalacion_deportiva/evento/get_count";
    $.ajax({
        url: url,
        type: 'GET',
        async: false,
        success: function (data) {
            result = data;
		//alert(result);
        }
    });
    return result;
}
/**************************************************/
/**************************************************/
/**************************************************/
function getEventosJSON() {
   // alert("tipoInstalacion 3");
    var selectBox = document.getElementById("selectBox");
    var tipoInstalacion = selectBox.options[selectBox.selectedIndex].value;
    var result = null;
  var url = localhost+"controler_evento_instalacion_deportiva/evento/get_events?tipoInstalacion="+tipoInstalacion;
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'json',
        async: false,
        success: function (data) {
            result = data;
        }
    });
    return result;
}
/**************************************************/
function saveEventosJSON(calEvent) {
		          var start= calEvent.start;
				  var end = calEvent.end;
				  var hour =start.getHours();
				  var minu =start.getMinutes();
				  var second= start.getSeconds();
				  var fechaStart= start.setHours(hour-6, minu, second);

				  // para fecha end
				  hour =end.getHours();
				  hour =end.getHours();
				  minu =end.getMinutes();
				  second= end.getSeconds();
				  end.setHours(hour-6, minu, second);
	              var result = null;
				  var selectBox = document.getElementById("selectBox");
                  var tipoInstalacion = selectBox.options[selectBox.selectedIndex].value;
                  var url = localhost+"controler_evento_instalacion_deportiva/evento/save?id="+calEvent.id+"&start="+start.toJSON()+"&end="+end.toJSON()+"&title="+calEvent.title+"&body="+calEvent.body+"&tipoInstalacion="+tipoInstalacion;
					$.ajax({
						url: url,
						type: 'GET',
						async: false,
						success: function (data) {
							result = data;
						//	alert(result);
						}
					});
					return result;
}
//*********************************************************
function updateEventosJSON(calEvent) {
		          var start= calEvent.start;
				  var end = calEvent.end;
				  var hour =start.getHours();
				  var minu =start.getMinutes();
				  var second= start.getSeconds();
				  start.setHours(hour-6, minu, second);
	
				  // para fecha end
				  hour =end.getHours();
				  hour =end.getHours();
				  minu =end.getMinutes();
				  second= end.getSeconds();
				  end.setHours(hour-6, minu, second);
	var result = null;
    $.getJSON(localhost+"controler_evento_instalacion_deportiva/evento/update?id="+calEvent.id+"&start="+start.toJSON()+"&end="+end.toJSON()+"&title="+calEvent.title+"&body="+calEvent.body);
}
//*********************************************************
function updateMoveEventosJSON(calEvent) {
		          var start =calEvent.start;
				  var end = calEvent.end;
				  var id= calEvent.id;
				   
				  // para fecha start
				  var hour =start.getHours();
				  var minu =start.getMinutes();
				  var second= start.getSeconds();
				  var fechaStart= start.setHours(hour-6, minu, second);
				  
				   // para fecha end
				  hour =end.getHours();
				  hour =end.getHours();
				  minu =end.getMinutes();
				  second= end.getSeconds();
				  end.setHours(hour-6, minu, second);
				  
	   $.getJSON(localhost+'controler_evento_instalacion_deportiva/evento/move?start='+start.toJSON()+'&end='+end.toJSON()+'&id='+id); 
}
